package main

import (
	"DMSRabbitMQ/common"
	"fmt"
	"github.com/pkg/errors"
	"log"
)

func main() {
	conn, err := common.GetConn()
	defer conn.Close()
	if err != nil {
		log.Printf("%+v", err)
		return
	}

	ch, err := conn.Channel()
	if err != nil {
		log.Printf("%+v", errors.Wrap(err, "ERR: fail to open a channel"))
		return
	}
	defer ch.Close()

	q, err := ch.QueueDeclare(
		"hello", // name
		false,   // durable
		false,   // delete when unused
		false,   // exclusive
		false,   // no-wait
		nil,     // arguments
	)
	if err != nil {
		log.Printf("%+v", errors.Wrap(err, "ERR: fail to declare a queue"))
		return
	}

	msgs, err := ch.Consume(
		q.Name, // queue
		"",     // consumer
		true,   // auto-ack
		false,  // exclusive
		false,  // no-local
		false,  // no-wait
		nil,    // args
	)
	if err != nil {
		log.Printf("%+v", errors.Wrap(err, "ERR: fail to register a consumer"))
		return
	}
	var doneCh chan struct{}

	go func() {
		for d := range msgs {
			fmt.Printf("Received a message: %s\n", d.Body)
		}
	}()

	fmt.Printf(" [*] Waiting for messages. To exit press CTRL+C\n")
	<-doneCh
}
